#!/bin/bash -
# echo "Loading \"${BASH_SOURCE[0]/$(dirname ${BOSS_Afterburner})\/}\""

# * ============================================================================= * #
# *   DESCRIPTION: Shell script that contains definitions of functions that are   * #
# *                used in the bash scripts this folder.                          * #
# *        AUTHOR: Remco de Boer (@IHEP), EMAIL: remco.de.boer@ihep.ac.cn         * #
# *  ORGANIZATION: IHEP, CAS (Beijing, CHINA)                                     * #
# *       CREATED: 12 May 2018                                                    * #
# *         USAGE: include in another bash script with this line:                 * #
# *                source Functions.sh                                            * #
# * ============================================================================= * #


function RunScript()
{
	if [[ ${#} -lt 1 ]]; then
		PrintError "${FUNCNAME[0]} requires at least 1 argument"
		return 1
	fi
	local scriptName="${1}"
	local executable="exe/${scriptName}.exe"
	shift
	make ${executable} > /dev/null && \
	./${executable} $@
}
export RunScript


function RunAnalysis()
{
	if [[ ${#} -lt 1 ]]; then
		PrintError "${FUNCNAME[0]} requires at least 1 argument"
		return 1
	fi

	local configName="${1}"
	if [[ ! -f "${configName}" ]]; then
		PrintError "Config file \"${configName}\" does not exist"
		return 1
	fi
	local analysis="$(echo ${configName} | cut -d'/' -f2)"
	local scriptName=""
	local numSlashes="${1//[^\/]}"
	numSlashes="${#numSlashes}"
	for i in $(seq 3 ${numSlashes}); do
		scriptName+="$(echo ${configName} | cut -d'/' -f$i)/"
		local executable="exe/${scriptName:0:-1}.exe"
		if [[ -f "${executable}" ]]; then
			make ${executable} > /dev/null && \
			./${executable} ${configName}
			if [[ $? == 0 ]]; then return 0; else return 1; fi
		fi
	done
	PrintError "Could not find corresponding executable\n  \"${executable}\""
	return 1

	local executable="exe/${scriptName}.exe"
	if [[ ${#} == 2 ]]; then
		local configName="configs/${2}.yaml"
	elif [[ ${#} == 3 ]]; then
		local configName="configs/${2}/${1}/${3}.yaml"
	fi
	local currentPath="$(pwd)"
	cd "${BOSS_Afterburner}"
	make ${executable} > /dev/null && \
	./${executable} ${configName}
	cd "${currentPath}"
}
export RunAnalysis


# function RunAnalysis()
# {
# 	if [[ ${#} -lt 1 ]]; then
# 		PrintError "${FUNCNAME[0]} requires at least 1 argument"
# 		return 1
# 	fi
# 	local scriptName="${1}"
# 	local executable="exe/${scriptName}.exe"
# 	if [[ ${#} == 2 ]]; then
# 		local configName="configs/${2}.yaml"
# 	elif [[ ${#} == 3 ]]; then
# 		local configName="configs/${2}/${1}/${3}.yaml"
# 	fi
# 	make ${executable} > /dev/null && \
# 	./${executable} ${configName}
# }
# export RunAnalysis


function RunAllAnalyses()
{
	local currentPath="$(pwd)"
	cd "${BOSS_Afterburner}"
	for script in $(ls run/*.sh); do
		local command="bash ${script}"
		echo "Running \"${command}\" ..."
		{ ${command}; } &> "${script/.sh/.log}"
		if [[ $? != 0 ]]; then
			PrintError "[${FUNCNAME[0]}] Failure"
			return $?
		fi
	done
	PrintSuccess "Successfully ran all analyses"
	cd "${currentPath}"
}
export RunAllAnalyses


function AttemptCommand()
{
	echo; echo
	PrintLine ${#1} "="
	PrintBold "${1}"
	PrintLine ${#1} "="
	echo
	${1}
	if [[ $? != 0 ]]; then
		PrintError "Failed to run \"${1}\""
		return 1
	fi
}
export AttemptCommand


function RunClang()
{
	local pathToFormat="."
	local ExtensionsToFormat=( C cpp cxx h hpp )
	if [[ ${#} == 1 ]]; then
		pathToFormat="${1}"
		if [[ ! -d "${pathToFormat}" ]]; then
			PrintError "Path \"${pathToFormat}\" does not exist"
			return 1
		fi
	fi
	for ext in ${ExtensionsToFormat[@]}; do
		clang-format -i $(find ${pathToFormat} -type f -iname "*.${ext}")
	done
}
export RunClang


function GenerateDoxygen()
{
	# * SCRIPT PARAMETERS * #
		local doxygenDir="doxygen"
		local doxygenFile="doxygen.in"
		local doxygenPath="${doxygenDir}/${doxygenFile}"
		local htmlDir="docs"
		local latexDir="latex"

	# * CHECK PARAMETERS * #
		if [ ! -d "${doxygenDir}" ]; then
			echo "\e[91mThis repository does not contain a Doxygen directory (\"${doxygenDir}\")\e[0m"
			exit
		fi
		if [ ! -f "${doxygenPath}" ]; then
			echo "\e[91mThis repository does not contain a Doxygen file \"${doxygenPath}\"\e[0m"
			exit
		fi

	# * PREPARE OUTPUT FOLDERS * #
		cd "${doxygenDir}"
		echo "Removed old Doxygen pages"
		rm -rf "../${htmlDir}"
		rm -rf "../${latexDir}"

	# * WRITE DOXYGEN PAGES * #
		echo "Writing Doxygen pages for repository $(basename $(pwd))"
		doxygen doxygen.in
		if [ $? == 0 ]; then
			echo -e "\e[92mSuccessfully created Doxygen documentation!\e[0m" # light green color code
		else
			echo -e "\e[91mFailed to create Doxygen documentation!\e[0m"     # light red color code
		fi

	cd - > /dev/null
}
export GenerateDoxygen


function MergeRootFiles()
{
	# * Check BOSS_Output parameter *
	if [[ ${#BOSS_Output} == 0 ]]; then
		PrintError "Bash parameter BOSS_Output has not been set"
		return 1
	fi

	# * Script parameters *
	local currentPath="$(pwd)"
	cd "${BOSS_Output}/root"
	local inputFolder="${1:-RhopiAlg/100,000_events}"
	local outputFile="${inputFolder}.root"

	# * Script parameters *
	if [[ -f "${outputFile}" ]]; then
		read -p "WARNING: Press ENTER to overwrite \"${outputFile}\" with ${numberOfFiles} merged files..."
	fi

	# * Check if files exist *
	local numberOfFiles=$(find ${inputFolder} -type f -name "*.root" | wc -l)
		if [[ ${numberOfFiles} == 0 ]]; then
			PrintError "No ROOT files of analysis type \"${inputFolder}\""
			return 1
		fi

	# * Merge ROOT files *
		hadd -f "${outputFile}" $(find ${inputFolder} -type f -name "*.root")

	cd "${currentPath}"
}
export MergeRootFiles